package com.ruoyi.app.controller.member.service.impl;

import com.ruoyi.app.controller.member.entity.BO.MemberConsumeTotalBO;
import com.ruoyi.app.controller.member.entity.BO.MemberDetailBO;
import com.ruoyi.app.controller.member.entity.BO.MemberVipTypeUpgradeBO;
import com.ruoyi.app.controller.member.entity.VO.MemberConsumeSearchVO;
import com.ruoyi.app.controller.member.entity.VO.MemberConsumeVO;
import com.ruoyi.app.controller.member.mapper.*;
import com.ruoyi.app.controller.member.service.IMemberService;
import com.ruoyi.app.controller.member.service.IMemberVipTypeService;
import com.ruoyi.app.controller.order.mapper.IMemberRechargeOrderMapper;
import com.ruoyi.app.controller.order.mapper.IShopCreditOrderMapper;
import com.ruoyi.app.controller.order.mapper.IShopPetrolOrderMapper;
import com.ruoyi.app.controller.product.mapper.IProductMapper;
import com.ruoyi.app.controller.shop.mapper.IShopConfigMapper;
import com.ruoyi.common.constant.MemberRechargeConstants;
import com.ruoyi.common.constant.OrderConstants;
import com.ruoyi.common.constant.SysConfigConstants;
import com.ruoyi.common.entity.DO.member.MemberDO;
import com.ruoyi.common.entity.DO.order.MemberRechargeOrderDO;
import com.ruoyi.common.entity.DO.order.ShopPetrolOrderDO;
import com.ruoyi.common.entity.VO.member.*;
import com.ruoyi.common.entity.VO.order.MemberRechargeOrderSearchVO;
import com.ruoyi.common.entity.VO.order.ShopOrderSearchVO;
import com.ruoyi.common.entity.VO.product.PetrolProductVO;
import com.ruoyi.common.entity.VO.shop.ShopProductSearchVO;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class MemberServiceImpl implements IMemberService {

    @Value("${api.host}")
    private String host;

    @Resource
    private IMemberVipTypeService memberVipTypeService;

    @Resource
    private IMemberRechargeOrderMapper rechargeOrderMapper;

    @Resource
    private IShopPetrolOrderMapper shopPetrolOrderMapper;

    @Resource
    private IShopCreditOrderMapper shopCreditOrderMapper;

    @Resource
    private IMemberMapper memberMapper;

    @Resource
    private IMemberBalanceRecordMapper balanceRecordMapper;

    @Resource
    private IMemberCreditRecordMapper creditRecordMapper;

    @Resource
    private IMemberCouponMapper memberCouponMapper;

    @Resource
    private IProductMapper productMapper;

//    @Resource
//    private IMemberVipBenefitExtMapper memberVipBenefitExtMapper;

    @Resource
    private IShopConfigMapper shopConfigMapper;

    @Override
    public MemberVO getProfileById(Long memberId) {
        memberVipTypeService.upgradeCheck(memberId);
        return memberMapper.getProfileById(memberId);
    }

    @Override
    public MemberDetailBO getAssetById(Long memberId) {
        memberVipTypeService.upgradeCheck(memberId);
        MemberDO memberAsset = memberMapper.getAssetById(memberId);
        if (null == memberAsset) {
            throw new UnauthorizedException("请重新登录！");
        }
        MemberDetailBO memberDetailBO = new MemberDetailBO();
        BeanUtils.copyProperties(memberAsset, memberDetailBO);
        memberDetailBO.setCouponNum(memberCouponMapper.getUnUseNum(memberId));
        //2023 02-12增加一个字段，积分商品未核销数量
        memberDetailBO.setPreExchangeNum(shopCreditOrderMapper.getPreExchangeNum(memberId));
        return memberDetailBO;

    }

    @Override
    public MemberDetailBO getDetailById(Long memberId) {
        memberVipTypeService.upgradeCheck(memberId);
        MemberDetailBO memberDetail = memberMapper.getDetailById(memberId);
        if (null == memberDetail) {
            throw new UnauthorizedException("请重新登录！");
        }
        // 默认头像处理
        String avatarW = host + "/logo/avatar-w.png";
        String avatarDefault = host + "/logo/avatar.png";
        if (memberDetail.getAvatar().equals(avatarDefault)) {
            memberDetail.setAvatarW(avatarW);
        } else {
            memberDetail.setAvatarW(memberDetail.getAvatar());
        }
        //优惠券数量
//        memberDetail.setCouponNum(memberCouponMapper.getUnUseNum(memberId));
        MemberVipTypeUpgradeBO memberVipTypeInfo = memberVipTypeService.getUpgradeInfoById(memberDetail.getVipTypeId(), memberDetail.getTotalRechargeAmount(), memberDetail.getTotalPetrolAmount());
        memberDetail.setVipTypeInfo(memberVipTypeInfo);
        ShopProductSearchVO searchVO = new ShopProductSearchVO();
        searchVO.setIsEnable(1);
        searchVO.setIsDelete(0);
        searchVO.setShopId(memberDetail.getShopId());
        searchVO.setMemberVipTypeId(memberDetail.getVipTypeId());
        searchVO.setSystemModule(SysConfigConstants.SystemModuleEnum.PETROL.getValue());
        // 根据当前会员等级获取加油权益列表
//        List<PetrolProductVO> petrolBenefits = productMapper.searchForBenefitList(searchVO);
        // 获取油品列表
        List<PetrolProductVO> productList = productMapper.searchPetrolList(searchVO);
        memberDetail.setTodayPetrolList(productList);
        //2023-03-05 获取独享折扣
//        if (!petrolBenefits.isEmpty()) {
//            for (PetrolProductVO one : petrolBenefits
//            ) {
//                if (null != one.getBenefitCreditRate() && BigDecimal.ZERO.compareTo(one.getBenefitCreditRate()) != 0) {
//                    one.setBenefitCreditRateName(one.getBenefitCreditRate().multiply(BigDecimal.valueOf(10)).setScale(1, BigDecimal.ROUND_HALF_UP).toString() + "折");
//                }
//                if (null != one.getBenefitDiscountRate() && BigDecimal.ZERO.compareTo(one.getBenefitDiscountRate()) != 0) {
//                    BigDecimal benefitDiscountRate = memberVipBenefitExtMapper.getBenefitDiscountRate(memberId,one.getProductId());
//                    if(null != benefitDiscountRate){
//                        one.setBenefitDiscountRate(benefitDiscountRate);
//                    }
//                    one.setBenefitDiscountRateName(one.getBenefitDiscountRate().multiply(BigDecimal.valueOf(10)).setScale(1, BigDecimal.ROUND_HALF_UP).toString() + "折");
//                    for (PetrolProductVO productInfo:productList){
//                        if(productInfo.getProductId().equals(one.getProductId())){
//                            one.setBenefitProductPrice(productInfo.getPrice().multiply(one.getBenefitDiscountRate()).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
//                        }
//                    }
//                }
//            }
//        }
//        memberDetail.setPetrolBenefitList(petrolBenefits);
        if (!("Y".equals(shopConfigMapper.searchValueByKey("memberVipType.upgrade.process.switch",memberDetail.getShopId()))))
        {
            memberDetail.setIsShowProgress(0);
            memberDetail.setIsShowProgressDesc(0);
        }else{
            memberDetail.setIsShowProgress(1);
            memberDetail.setIsShowProgressDesc(1);
        }
        return memberDetail;
    }


    @Override
    public MemberDO getPasswordInfoById(Long memberId) {
        return memberMapper.getPasswordInfoById(memberId);
    }

    @Override
    public MemberDO getMemberForToken(Long memberId) {
        if (memberId == 0) {
            return memberMapper.getRandomMember();
        } else {
            return memberMapper.getForTokenById(memberId);
        }
    }

    @Override
    public void updateProfile(MemberVO memberVO) {
        MemberDO memberInfo = memberMapper.selectByPrimaryKey(memberVO.getId());
        MemberDO memberUpdate = new MemberDO();
        if (null == memberInfo) {
            throw new UnauthorizedException("请重新登录！");
        }
        memberUpdate.setId(memberInfo.getId());
        memberUpdate.setUpdateTime(new Date());
        memberUpdate.setUpdateBy("会员编辑资料");
        if (null != memberVO.getSex()) {
            memberUpdate.setSex(memberVO.getSex());
        }
        if (StringUtils.isNotEmpty(memberVO.getAvatar())) {
            memberUpdate.setAvatar(memberVO.getAvatar());
        }
        if (StringUtils.isNotEmpty(memberVO.getNickname())) {
            memberUpdate.setNickname(memberVO.getNickname());
        }
        if (StringUtils.isNotEmpty(memberVO.getUserName())) {
            memberUpdate.setUserName(memberVO.getUserName());
        }
        if (StringUtils.isNotEmpty(memberVO.getBirthday())) {
            memberUpdate.setBirthday(memberVO.getBirthday());
        }
        if (StringUtils.isNotEmpty(memberVO.getEmail())) {
            memberUpdate.setEmail(memberVO.getEmail());
        }
        memberMapper.updateByPrimaryKeySelective(memberUpdate);
    }

    @Override
    public void updatePrivate(MemberDO updateInfo) {
        MemberDO memberInfo = memberMapper.selectByPrimaryKey(updateInfo.getId());
        MemberDO memberUpdate = new MemberDO();
        if (null == memberInfo) {
            throw new UnauthorizedException("请重新登录！");
        }
        memberUpdate.setId(memberInfo.getId());
        memberUpdate.setUpdateTime(new Date());
        memberUpdate.setUpdateBy(updateInfo.getUpdateBy());
        if (StringUtils.isNotEmpty(updateInfo.getPaypassword())) {
            memberUpdate.setPaypassword(updateInfo.getPaypassword());
        }
        memberMapper.updateByPrimaryKeySelective(memberUpdate);

    }

    @Override
    public List<MemberBalanceRecordVO> searchBalanceRecordList(MemberBalanceRecordSearchVO memberBalanceRecordSearchVO) {
        List<MemberBalanceRecordVO> balanceRecordList = balanceRecordMapper.searchList(memberBalanceRecordSearchVO);
        String logo;
        for (MemberBalanceRecordVO one : balanceRecordList
        ) {
            one.setOrderSn(one.getLinkSn());
            logo = MemberRechargeConstants.LinkModelEnum.match(one.getLinkModel()).getLogo();
            if (StringUtils.isNotEmpty(logo)) {
                one.setLogo(logo);
            }
        }
        return balanceRecordList;
    }

    @Override
    public List<MemberCreditRecordVO> searchCreditRecordList(MemberCreditRecordSearchVO memberCreditRecordSearchVO) {
        List<MemberCreditRecordVO> creditRecordList = creditRecordMapper.searchList(memberCreditRecordSearchVO);
        String logo;
        for (MemberCreditRecordVO one : creditRecordList
        ) {
            one.setOrderSn(one.getLinkSn());
            logo = MemberRechargeConstants.LinkModelEnum.match(one.getLinkModel()).getLogo();
            if (StringUtils.isNotEmpty(logo)) {
                one.setLogo(logo);
            }
        }
        return creditRecordList;
    }

    @Override
    public List<MemberConsumeVO> searchConsumeList(MemberConsumeSearchVO searchVO) {
        List<MemberConsumeVO> consumeList = new ArrayList<>();
        MemberRechargeOrderSearchVO searchVO2 = new MemberRechargeOrderSearchVO();
        ShopOrderSearchVO searchVO3 = new ShopOrderSearchVO();
        searchVO2.setMemberId(searchVO.getMemberId());
        searchVO2.setOrderStatus(OrderConstants.OrderStatusEnum.COMPLETE.getValue());
        searchVO2.setPayStatus(OrderConstants.OrderPayStatusEnum.COMPLETE.getValue());
        searchVO2.setFromDate(searchVO.getFromDate());
        searchVO2.setToDate(searchVO.getToDate());
        searchVO2.setYearMonth(searchVO.getYearMonth());

        searchVO3.setMemberId(searchVO.getMemberId());
        searchVO3.setOrderStatus(OrderConstants.OrderStatusEnum.COMPLETE.getValue());
        searchVO3.setPayStatus(OrderConstants.OrderPayStatusEnum.COMPLETE.getValue());
        searchVO3.setFromDate(searchVO.getFromDate());
        searchVO3.setToDate(searchVO.getToDate());
        searchVO3.setYearMonth(searchVO.getYearMonth());

        List<MemberRechargeOrderDO> rechargeOrderList = rechargeOrderMapper.searchList(searchVO2);
        MemberConsumeVO tmp;
        for (MemberRechargeOrderDO one : rechargeOrderList
        ) {
            tmp = new MemberConsumeVO();
            tmp.setLogo(host+"/logo/recharge.png");
            tmp.setChangeAmount(one.getAmount());
            tmp.setDiscountAmount(one.getDiscountAmount());
            tmp.setGiftAmount(one.getGiftAmount());
            tmp.setChangeType(MemberRechargeConstants.ChangeTypeEnum.INCREASE.getValue());
            tmp.setCreateTime(one.getCreateTime());
            tmp.setLinkModule(SysConfigConstants.SystemModuleEnum.RECHARGE.getValue());
            tmp.setOrderSn(one.getOrderSn());
            tmp.setTitle("充值");
            tmp.setRemark("");
            consumeList.add(tmp);
        }
        List<ShopPetrolOrderDO> shopPetrolOrderList = shopPetrolOrderMapper.searchList(searchVO3);
        for (ShopPetrolOrderDO one : shopPetrolOrderList
        ) {
            tmp = new MemberConsumeVO();
            tmp.setOrderSn(one.getOrderSn());
            tmp.setChangeAmount(one.getPayCost());
            tmp.setDiscountAmount(one.getDiscountAmount());
            tmp.setChangeType(MemberRechargeConstants.ChangeTypeEnum.DECREASE.getValue());
            tmp.setCreateTime(one.getCreateTime());
            tmp.setLinkModule(SysConfigConstants.SystemModuleEnum.PETROL.getValue());
            tmp.setTitle(one.getProductName() + "，" + one.getProductQuantity() + "升");
            if (one.getPayWay() == OrderConstants.OrderPayWayEnum.WX_PAY.getValue()) {
                tmp.setLogo(host+"/logo/wxpay.png");
                tmp.setRemark("加油-微信支付");
            } else {
                tmp.setLogo(host+"/logo/balance.png");
                tmp.setRemark("加油-余额支付");
            }
            consumeList.add(tmp);
        }
        consumeList.sort((o1, o2) -> {
            long diff = o1.getCreateTime().getTime() - o2.getCreateTime().getTime();
            if (diff > 0) {
                return -1;
            } else {
                return 1;
            }
        });
        return consumeList;
    }

    @Override
    public MemberConsumeTotalBO getConsumeTotal(MemberConsumeSearchVO searchVO) {
        MemberConsumeTotalBO consumeTotalBO = new MemberConsumeTotalBO();
        consumeTotalBO.setChargeAmount(rechargeOrderMapper.getTotalAmountByMonth(searchVO.getMemberId(), searchVO.getYearMonth()));
        consumeTotalBO.setDiscountAmount(shopPetrolOrderMapper.getTotalDiscountAmountByMonth(searchVO.getMemberId(), searchVO.getYearMonth()));
        consumeTotalBO.setPayAmount(shopPetrolOrderMapper.getTotalPayCostByMonth(searchVO.getMemberId(), searchVO.getYearMonth()));
        if(null == consumeTotalBO.getChargeAmount()){
            consumeTotalBO.setChargeAmount(BigDecimal.ZERO);
        }
        if(null == consumeTotalBO.getDiscountAmount()){
            consumeTotalBO.setDiscountAmount(BigDecimal.ZERO);
        }
        if(null == consumeTotalBO.getPayAmount()){
            consumeTotalBO.setPayAmount(BigDecimal.ZERO);
        }
        return consumeTotalBO;
    }

}
